package com.dynabook.ems.constant;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Random;

/**
 * 邮件模板类
 * 用于样品管理系统的邮件通知
 *
 */
@Component
public class MailTemplate {
    
    // 邮件主题常量
    public static final String SUBJECT_BORROW_APPLY = "[样品借出审批] Workflow from ";
    public static final String SUBJECT_BORROW_APPLY_APPROVE_FROM_SECTION = "[样品借出审批通过] Workflow from ";
    public static final String SUBJECT_BORROW_APPLY_REJECT_FROM_SECTION = "[样品借出审批拒绝] Workflow from ";
    
    public static final String SUBJECT_BORROW_APPLY_APPROVE_FROM_SAMPLE = "[样品分配通过] Workflow from ";
    public static final String SUBJECT_BORROW_APPLY_REJECT_FROM_SAMPLE = "[样品分配拒绝] Workflow from ";
    public static final String SUBJECT_WORK_ORDER_APPROVAL = "[工单待审批] Workflow from ";
    public static final String SUBJECT_WORK_ORDER_BATCH_REJECT = "[工单审批拒绝] Workflow from ";
    public static final String SUBJECT_WORK_ORDER_BATCH_APPROVE = "[工单审批同意] Workflow from ";
    public static final String SUBJECT_WORK_ORDER_PM_COMPLETE = "[工单PM完工] Workflow from ";
    public static final String SUBJECT_WORK_ORDER_SAMPLE_ACCEPTANCE = "[工单验收完成] Workflow from ";

    public static final String SUBJECT_RETURN_SAMPLE = "[样品归还] Workflow from ";
    
    public static final String SUBJECT_DELETE_APPLY = "[样品删除审批] Workflow from ";
    public static final String SUBJECT_DELETE_APPLY_APPROVE_FROM_SECTION = "[样品删除审批通过] Workflow from ";
    public static final String SUBJECT_DELETE_APPLY_REJECT_FROM_SECTION = "[样品删除审批拒绝] Workflow from ";
    
    public static final String SUBJECT_SCRAP_APPLY = "[样品报废审批] Workflow from ";
    public static final String SUBJECT_SCRAP_APPLY_APPROVE_FROM_SAMPLE = "[样品报废审批通过] Workflow from ";
    public static final String SUBJECT_SCRAP_APPLY_REJECT_FROM_SAMPLE = "[样品报废审批拒绝] Workflow from ";
    public static final String SUBJECT_RECEIPT_APPLY = "[INFO]研发账册数据入库异常";
    @Value("${spring.ems_url}")
    private   String EMS_URL;

    
    private static final Random random = new Random();
    /**
     * 入库异常邮件内容
     */
    public  String getReceiptApply() {
        return "<p>Dear Sir/Madam</p>" +
                "<p> 以下研发样品型号ITEM_CODE无法匹配大样品型号分类表数据,请相关担当帮忙确认!</p>";
    }
    public String getReceiptSubject(){
        return SUBJECT_RECEIPT_APPLY;
    }

    /**
     * 获取借出申请邮件内容
     */
    public  String getBorrowApply(String section, String user) {
        return "<p>Dear Managers</p>" +
               "<p>" + section + "课的" + user + "提交了样品借出申请, 请登录样品管理系统确认及审批, 谢谢!</p>";
    }
    
    /**
     * 获取部门审批通过回复内容
     */
    public  String getReplyApproveBorrowApplyFromSection() {
        return "<p>Dear Sample Manager</p>" +
               "<p>如下样机审批通过, 请登录样品管理系统确认, 谢谢!</p>";
    }
    
    /**
     * 获取部门审批拒绝回复内容
     */
    public  String getReplyRejectBorrowApplyFromSection(String user) {
        return "<p>Dear " + user + "</p>" +
               "<p>如下样机审批拒绝, 请登录样品管理系统确认, 谢谢!</p>";
    }
    
    /**
     * 获取样品分配通过回复内容
     */
    public  String getReplyApproveBorrowApplyFromSample(String user) {
        return "<p>Dear " + user + "</p>" +
               "<p>如下样机分配通过, 请及时到样品管理库取得样品, 谢谢!</p>";
    }
    
    /**
     * 获取样品分配拒绝回复内容
     */
    public  String getReplyRejectBorrowApplyFromSample(String user) {
        return "<p>Dear " + user + "</p>" +
               "<p>如下样机分配拒绝, 请登录样品管理系统确认, 谢谢</p>";
    }

    public  String getWorkOrderApproval() {
        return "<p>Dear Sir/Madam </p>" +
                "<p>以下新建生产工单请确认并审批，谢谢</p>";
    }
    
    /**
     * 获取工单批量拒绝邮件内容
     */
    public String getWorkOrderBatchReject() {
        return "<p>Dear Sir/Madam</p>" +
                "<p>以下工单已被批量拒绝，请确认并修改此工单，谢谢</p>";
    }
    
    /**
     * 获取工单批量同意邮件内容
     */
    public String getWorkOrderBatchApprove() {
        return "<p>Dear Sir/Madam</p>" +
                "<p>以下工单已审批通过，请跟踪后续借出流程，谢谢</p>";
    }
    
    /**
     * 获取工单PM完工邮件内容
     */
    public String getWorkOrderPmComplete() {
        return "<p>Dear Sir/Madam</p>" +
                "<p>以下工单已完成生产，请及时进行验收，谢谢</p>";
    }
    
    /**
     * 获取工单样品管理员验收完成邮件内容
     */
    public String getWorkOrderSampleAcceptance() {
        return "<p>Dear Sir/Madam</p>" +
                "<p>以下工单已完成验收，工单流程已全部完成，谢谢</p>";
    }
    
    /**
     * 获取归还样品通知内容
     */
    public  String getReturnSample(String user) {
        return "<p>Dear " + user + "</p>" +
               "<p>如下样机已归还, 请登录样品管理系统确认, 谢谢</p>";
    }
    
    /**
     * 获取删除申请邮件内容
     */
    public  String getDeleteApply(String section, String user) {
        return "<p>Dear Managers</p>" +
               "<p>" + section + "课的" + user + "提交了样品删除申请, 请登录样品管理系统确认及审批, 谢谢!</p>";
    }
    
    /**
     * 获取删除审批通过内容
     */
    public  String getDeleteApproveFromSection() {
        return "<p>Dear Sample Manager</p>" +
               "<p>如下样机审批通过, 请登录样品管理系统确认, 谢谢!</p>";
    }
    
    /**
     * 获取删除审批拒绝内容
     */
    public  String getDeleteRejectFromSection() {
        return "<p>Dear Sample Manager</p>" +
               "<p>如下样机审批拒绝, 请登录样品管理系统确认, 谢谢!</p>";
    }
    
    /**
     * 获取报废申请内容
     */
    public  String getScrapApply() {
        return "<p>Dear Sample Managers</p>" +
               "<p>您收到了样品报废申请, 请登录样品管理系统确认及审批, 谢谢!</p>";
    }
    
    /**
     * 获取报废审批通过内容
     */
    public  String getScrapApproveFromSample() {
        return "<p>Dear Sample Manager</p>" +
               "<p>如下样机审批通过, 请登录样品管理系统确认, 谢谢!</p>";
    }
    
    /**
     * 获取报废审批拒绝内容
     */
    public  String getScrapRejectFromSample() {
        return "<p>Dear Sample Manager</p>" +
               "<p>如下样机审批拒绝, 请登录样品管理系统确认, 谢谢!</p>";
    }
    
    /**
     * 获取导入通知内容
     */
    public  String getImportNotice() {
        return "<p>Dear All</p>" +
               "<p>大家好, 以下样品已入库, 如果有需要可通过申请再来领取</p>" +
               "<p>点击<a style=\"font-size:20px;\" href=\"" + EMS_URL + "\">此链接</a>确认详情</p>";
    }
    
    /**
     * 获取完整邮件内容
     */
    public  String getContent(String mainBody, String tables) {
        return "<html charset=\"utf-8\">" +
               "    <head>" +
                        getCSSStyle() +
               "    </head>" +
               "    <body>" +
                        mainBody +
                        getTableData(tables) +
                        getFooter() +
               "    </body>" +
                "</html>";
    }
    
    /**
     * 获取导入邮件内容
     */
    public  String getImportContent(String mainBody, String tables) {
        return "<html charset=\"utf-8\">" +
                "    <head>" +
                        getCSSStyle() +
                "    </head>" +
                "    <body>" +
                        mainBody +
                        getImportTableData(tables) +
                "    </body>" +
                "</html>";
    }
    
    /**
     * 获取申请邮件内容
     */
    public  String getApplyContent(String mainBody, String tables) {
        return "<html charset=\"utf-8\">" +
            "    <head>" +
            getCSSStyle() +
            "    </head>" +
            "    <body>" +
            mainBody +
            getApplyTableData(tables) +
            getFooter() +
            "    </body>" +
            "</html>";
    }
    public  String getReceiptContent( List<String> itemCodeList) {
        return "<html charset=\"utf-8\">" +
                "    <head>" +
                getCSSStyle() +
                "    </head>" +
                "    <body>" +
                getReceiptApply() +
                getReceiptTableData(itemCodeList) +
                getReceiptFooter() +
                "    </body>" +
                "</html>";
    }
    
    /**
     * 获取拒绝邮件内容
     */
    public  String getRejectContent(String mainBody, String tables) {
        return "<html charset=\"utf-8\">" +
            "    <head>" +
            getCSSStyle() +
            "    </head>" +
            "    <body>" +
            mainBody +
            getRejectTableData(tables) +
            getFooter() +
            "    </body>" +
            "</html>";
    }

    private String getReceiptTableData(List<String> itemCodeList){
        try {
            if (itemCodeList == null || itemCodeList.isEmpty()) {
                return "<p>暂无数据</p>";
            }
            
            StringBuilder tables = new StringBuilder();
            tables.append("<tr>")
                  .append("  <th>ITEM_CODE</th>")
                  .append("</tr>");
            
            for (int i = 0; i < itemCodeList.size(); i++) {
                String itemCode = itemCodeList.get(i);
                String cssClass = (i % 2 == 0) ? "alt" : "";
                
                tables.append("<tr class=\"").append(cssClass).append("\">")
                      .append("    <td>").append(itemCode != null ? itemCode : "").append("</td>")
                      .append("</tr>");
            }
            
            return "<table id=\"customers\">" + tables.toString() + "</table>";
            
        } catch (Exception e) {
            e.printStackTrace();
            return "<p>表格数据解析错误</p>";
        }
    }
    
    /**
     * 解析表格数据（基础版）
     */
    private  String getTableData(String json) {
        try {
            JSONArray jsonArray = JSONUtil.parseArray(json);
            
            StringBuilder tables = new StringBuilder();
            tables.append("<tr>")
                  .append("  <th>样品编号</th>")
                  .append("  <th>样品名称</th>")
                  .append("  <th>备注</th>")
                  .append("</tr>");
            
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject item = jsonArray.getJSONObject(i);
                String cssClass = (i % 2 == 0) ? "alt" : "";
                
                tables.append("<tr class=\"").append(cssClass).append("\">")
                      .append("    <td>").append(item.getStr("id", "")).append("</td>")
                      .append("    <td>").append(item.getStr("name", "")).append("</td>")
                      .append("    <td>").append(item.getStr("desc", "")).append("</td>")
                      .append("</tr>");
            }
            
            return "<table id=\"customers\">" + tables.toString() + "</table>";
            
        } catch (Exception e) {
            e.printStackTrace();
            return "<p>表格数据解析错误</p>";
        }
    }
    
    /**
     * 解析导入表格数据
     */
    private  String getImportTableData(String json) {
        try {
            JSONArray jsonArray = JSONUtil.parseArray(json);
            
            StringBuilder tables = new StringBuilder();
            tables.append("<tr>")
                  .append("  <th>样品编号</th>")
                  .append("  <th>样品名称</th>")
                  .append("  <th>序列号</th>")
                  .append("  <th>型号</th>")
                  .append("  <th>备注</th>")
                  .append("  <th>课</th>")
                  .append("  <th>负责人</th>")
                  .append("</tr>");
            
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject item = jsonArray.getJSONObject(i);
                String cssClass = (i % 2 == 0) ? "alt" : "";
                
                tables.append("<tr class=\"").append(cssClass).append("\">")
                      .append("    <td>").append(item.getStr("id", "")).append("</td>")
                      .append("    <td>").append(item.getStr("name", "")).append("</td>")
                      .append("    <td>").append(item.getStr("sn", "")).append("</td>")
                      .append("    <td>").append(item.getStr("pn", "")).append("</td>")
                      .append("    <td>").append(item.getStr("remark", "")).append("</td>")
                      .append("    <td>").append(item.getStr("section", "")).append("</td>")
                      .append("    <td>").append(item.getStr("charge", "")).append("</td>")
                      .append("</tr>");
            }
            
            return "<table id=\"customers\">" + tables.toString() + "</table>";
            
        } catch (Exception e) {
            e.printStackTrace();
            return "<p>表格数据解析错误</p>";
        }
    }
    
    /**
     * 解析申请表格数据
     */
    private  String getApplyTableData(String json) {
        try {
            JSONArray jsonArray = JSONUtil.parseArray(json);
            
            StringBuilder tables = new StringBuilder();
            tables.append("<tr>")
                  .append("  <th>样品编号</th>")
                  .append("  <th>样品名称</th>")
                  .append("  <th>预计归还时间</th>")
                  .append("  <th>备注</th>")
                  .append("</tr>");
            
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject item = jsonArray.getJSONObject(i);
                String cssClass = (i % 2 == 0) ? "alt" : "";
                
                tables.append("<tr class=\"").append(cssClass).append("\">")
                      .append("    <td>").append(item.getStr("id", "")).append("</td>")
                      .append("    <td>").append(item.getStr("name", "")).append("</td>")
                      .append("    <td>").append(item.getStr("predictDate", "")).append("</td>")
                      .append("    <td>").append(item.getStr("desc", "")).append("</td>")
                      .append("</tr>");
            }
            
            return "<table id=\"customers\">" + tables.toString() + "</table>";
            
        } catch (Exception e) {
            e.printStackTrace();
            return "<p>表格数据解析错误</p>";
        }
    }
    
    /**
     * 解析拒绝表格数据
     */
    private  String getRejectTableData(String json) {
        try {
            JSONArray jsonArray = JSONUtil.parseArray(json);
            
            StringBuilder tables = new StringBuilder();
            tables.append("<tr>")
                  .append("  <th>样品编号</th>")
                  .append("  <th>样品名称</th>")
                  .append("  <th>拒绝原因</th>")
                  .append("  <th>备注</th>")
                  .append("</tr>");
            
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject item = jsonArray.getJSONObject(i);
                String cssClass = (i % 2 == 0) ? "alt" : "";
                
                tables.append("<tr class=\"").append(cssClass).append("\">")
                      .append("    <td>").append(item.getStr("id", "")).append("</td>")
                      .append("    <td>").append(item.getStr("name", "")).append("</td>")
                      .append("    <td>").append(item.getStr("rejectReason", "")).append("</td>")
                      .append("    <td>").append(item.getStr("desc", "")).append("</td>")
                      .append("</tr>");
            }
            
            return "<table id=\"customers\">" + tables.toString() + "</table>";
            
        } catch (Exception e) {
            e.printStackTrace();
            return "<p>表格数据解析错误</p>";
        }
    }
    private  String getReceiptFooter() {
        return "<p>以上</p><p>谢谢</p>";
    }

    /**
     * 获取邮件底部内容
     */
    private  String getFooter() {
        return "<p></p><p style=\"margin-top: 10px\">点击<a href=\"" + EMS_URL + "\">此链接</a>确认详情</p>";
    }
    
    /**
     * 获取CSS样式
     */
    private  String getCSSStyle() {
        return "<style type=\"text/css\">" +
            "     p,a {" +
            "        font-family:\"Trebuchet MS\", Arial, Helvetica, sans-serif;" +
            "        font-size:20px;" +
            "        margin: 8px 0px 4px 0px;" +
            "        color: Purple" +
            "     }" +
            "     #customers{" +
            "        font-family:\"Trebuchet MS\", Arial, Helvetica, sans-serif;" +
            "        border-collapse:collapse;" +
            "     }" +
            "     #customers td , #customers th {" +
            "        font-size:20px;" +
            "        font-weight:normal;" +
            "        border:1px solid #D4D4D4;" +
            "        text-align: left;" +
            "        padding: 5px 5px 5px 5px;" +
            "     }" +
            "     #customers th {" +
            "        background-color:" + getRandomColor() +
            "        color:#ffffff;" +
            "      }" +
            "      #customers tr.alt td {" +
            "         color:#000000;" +
            "         background-color:#F6F4F0;" +
            "      }" +
            "</style>";
    }
    
    /**
     * 获取随机颜色
     * 别问, 问就是生成所有的颜色满足领导一切需求
     */
    private  String getRandomColor() {
        // List<String> colors = Arrays.asList("Crimson", "Wheat", "Peru", "LightSeaGreen", "BlueViolet", "RoyalBlue", "Black");
        // return colors.get(random.nextInt(colors.size())) + ";";
        return "LightSeaGreen;";
    }
}